//
//  FileFunctions.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/4/5.
//

import Foundation
import UIKit
import AVFoundation


// MARK: - 图片文件管理
class ImageFileManager: FileManagerTool {
    private static let imageSubdirectory = "Images"
    
    /// 保存图片到指定目录
    static func saveImage(_ image: UIImage, _ fileName: String, _ directory: Directory = .documents) -> Bool {
        guard let data = image.pngData() else {
            showLog("❌ 图片转换失败")
            return false
        }
        
        guard let dirURL = createSubdirectoryIfNeeded(at: directory, subdirectory: imageSubdirectory) else {
            return false
        }
        
        let fileURL = dirURL.appendingPathComponent(fileName)
        do {
            try data.write(to: fileURL)
            showLog("✅ 图片保存成功: \(fileURL.path)")
            return true
        } catch {
            showLog("❌ 图片保存失败: \(error)")
            return false
        }
    }
    
    /// 加载图片
    static func loadImage(_ fileName: String, _ directory: Directory = .documents) -> UIImage? {
        let fileURL = directory.url
            .appendingPathComponent(imageSubdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 图片文件不存在: \(fileURL.path)")
            return nil
        }
        
        return UIImage(contentsOfFile: fileURL.path)
    }
    
    /// 加载图片- 获取路径
    static func loadImagePath(_ fileName: String, _ directory: Directory = .documents) -> String? {
        let fileURL = directory.url
            .appendingPathComponent(imageSubdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 图片文件不存在2: \(fileName)")
            showLog("⚠️ 图片文件不存在2: \(fileURL.path)")
            return nil
        }
        
        return fileURL.path
    }
}

// MARK: - 视频文件管理
class VideoFileManager: FileManagerTool {
    private static let videoSubdirectory = "Videos"
    
    /// 保存视频（从本地URL复制），保存是需要后缀如.mp4, 会自动获取，所以return返回的是带后缀的名称
    static func saveVideo(_ sourceURL: URL, _ fileName: String, _ directory: Directory = .documents) -> String {
        guard let dirURL = createSubdirectoryIfNeeded(at: directory, subdirectory: videoSubdirectory) else {
            return fileName
        }
        
        // 自动从源URL提取扩展名
        let fileExtension = sourceURL.pathExtension
        let fileNameWithExtension = (fileName as NSString).appendingPathExtension(fileExtension) ?? fileName
        
        let targetURL = dirURL.appendingPathComponent(fileNameWithExtension)
        do {
            try FileManager.default.copyItem(at: sourceURL, to: targetURL)
            showLog("✅ 视频保存成功: \(targetURL.path)")
            return fileNameWithExtension
        } catch {
            showLog("❌ 视频保存失败: \(error)")
            return fileName
        }
    }
    
    /// 加载视频URL
    static func loadVideoURL(_ fileName: String, _ directory: Directory = .documents) -> URL? {
        let fileURL = directory.url
            .appendingPathComponent(videoSubdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 视频文件不存在: \(fileURL.path)")
            return nil
        }
        
        return fileURL
    }
    
    /// 生成视频缩略图
    static func loadThumbnail(_ fileName: String, _ directory: Directory = .documents) -> UIImage? {
        guard let videoURL = loadVideoURL(fileName, directory) else {
            showLog("❌ 无法获取视频URL")
            return nil
        }
        
        // 确认文件存在
        if !FileManager.default.fileExists(atPath: videoURL.path) {
            showLog("❌ 视频文件不存在于路径: \(videoURL.path)")
            return nil
        }
        
        let asset = AVAsset(url: videoURL)
        // 检查是否有视频轨道
        guard !asset.tracks(withMediaType: .video).isEmpty else {
            showLog("❌ 视频无有效轨道或格式不支持")
            return nil
        }
        
        let generator = AVAssetImageGenerator(asset: asset)
        generator.appliesPreferredTrackTransform = true
        generator.requestedTimeToleranceBefore = .positiveInfinity
        generator.requestedTimeToleranceAfter = .positiveInfinity
        
        // 获取视频开始处的缩略图
        let time = CMTime(seconds: 0, preferredTimescale: 600)
        var resultImage: UIImage?
        let semaphore = DispatchSemaphore(value: 0)
        
        generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { _, cgImage, _, result, error in
            defer { semaphore.signal() }
            
            if let error = error {
                showLog("❌ 缩略图生成失败: \(error)")
                return
            }
            
            guard let cgImage = cgImage, result == .succeeded else {
                showLog("❌ 无法获取缩略图")
                return
            }
            
            resultImage = UIImage(cgImage: cgImage)
        }
        
        _ = semaphore.wait(timeout: .distantFuture)
        return resultImage
    }
}

// MARK: - 音频文件管理
class AudioFileManager: FileManagerTool {
    private static let audioSubdirectory = "audio"
    
    /// 保存语音文件（从Data对象），保存时需要后缀如.m4a，会自动获取或使用默认值
    static func saveAudio(_ audioData: Data, _ fileName: String, _ directory: Directory = .documents) -> String {
        guard let dirURL = createSubdirectoryIfNeeded(at: directory, subdirectory: audioSubdirectory) else {
            return fileName
        }
        
        // 尝试从文件名提取扩展名，如果没有则使用默认扩展名
        let fileExtension = (fileName as NSString).pathExtension
    
        // 确保文件名包含扩展名
        let fileNameWithExtension = (fileName as NSString).appendingPathExtension(fileExtension) ?? fileName
        let targetURL = dirURL.appendingPathComponent(fileNameWithExtension)
    
        
        do {
            try audioData.write(to: targetURL, options: .atomic)
            showLog("✅ 语音保存成功: \(targetURL.path)")
            return fileNameWithExtension
        } catch {
            showLog("❌ 语音保存失败: \(error)")
            return fileName
        }
    }
    
    /// 加载语音URL
    static func loadAudioURL(_ fileName: String, _ directory: Directory = .documents) -> URL? {
        let fileURL = directory.url
            .appendingPathComponent(audioSubdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 语音文件不存在: \(fileURL.path)")
            return nil
        }
        
        return fileURL
    }
    
    /// 加载语音Data
    static func loadAudioData(_ fileName: String, _ directory: Directory = .documents) -> Data? {
        guard let fileURL = loadAudioURL(fileName, directory) else {
            return nil
        }
        
        do {
            let audioData = try Data(contentsOf: fileURL)
            return audioData
        } catch {
            showLog("❌ 语音加载失败: \(error)")
            return nil
        }
    }
}
